package com.blog.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.blog.dao.BaseDao;
import com.blog.dao.ChattingRecordsDao;
import com.blog.entity.ChattingRecord;

public class ChattingRecordsDaoImpl implements ChattingRecordsDao {

	@Override
	public List<ChattingRecord> selectRecordBySendIdAndReceiveId(int sendId, int receiveId, int num) {
		// TODO Auto-generated method stub
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		List<ChattingRecord> chattingRecordList = new ArrayList<ChattingRecord>();
		String sql = "SELECT * FROM chattingrecords where (sendId = ? AND receiveId = ?) OR (sendId = ? AND receiveId = ?) ORDER BY sendDate DESC LIMIT 0,?;";
		ChattingRecord selectChatRecord = null;
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1,sendId);
			ps.setInt(2,receiveId);
			ps.setInt(3,receiveId);
			ps.setInt(4,sendId);
			ps.setInt(5,num);
			res = ps.executeQuery();
			while(res.next()) {
				selectChatRecord = new ChattingRecord();
				selectChatRecord.setChatRecordId(res.getInt("chatRecordId"));
				selectChatRecord.setCharText(res.getString("charText"));
				selectChatRecord.setSendId(res.getInt("sendId"));
				selectChatRecord.setReceiveId(res.getInt("receiveId"));
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date dt = null;
				try {
					dt = format.parse(format.format(res.getTimestamp("sendDate")));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					System.out.println("转换成Date的String不是规范值");
					e.printStackTrace();
				}
				selectChatRecord.setSendDate(dt);
				chattingRecordList.add(selectChatRecord);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(res, ps, con);
		}
		return chattingRecordList;
	}

}
